<template>
	<view class="addAdress">
		<Navigation title="新建收货地址" background="#fff" />
		<view class="bg ph-40">
			<u--form labelPosition="left" :model="model" ref="formRef" labelWidth="80"
				:labelStyle="{ fontSize: '32rpx', fontWeight: '500', color: '#222222' }" :rules="rules">
				<u-form-item label="联系人" prop="name" borderBottom>
					<u--input v-model="model.name" border="none" placeholder="请输入联系人" fontSize="16" clearable></u--input>
				</u-form-item>
				<u-form-item label="手机号" prop="mobile" borderBottom>
					<u--input v-model="model.mobile" type="number" border="none" placeholder="请填写收货人手机号" fontSize="16"
						clearable></u--input>
				</u-form-item>
				<u-form-item label="所在地区" prop="areaId" borderBottom>
					<view class="f ai-c jc-s-b" @click="loaction">
						<u--input v-model="cityName" border="none" placeholder="请选择所在地区" fontSize="16" clearable readonly>
						</u--input>
						
						<view class="f ai-c">
							<view class="fs-32 fw-500 text-color4">定位</view>
							<u-icon name="map" class="mr-12"></u-icon>
							
						</view>
					</view>
				</u-form-item>
				<u-form-item prop="detailAddress" borderBottom>

					<view class="f ai-c jc-s-b mb-20">
						<view class="fs-32" style="font-weight: bold;">详细地址</view>
						
					</view>
					<textarea v-model="model.detailAddress" placeholder="请填写详细地址" v-if="!showCity"></textarea>
				</u-form-item>
			</u--form>
		</view>
		<view class="mt-24 f ai-c jc-s-b h-120 bg ph-40">
			<view class="f f1 ai-c">
				<view class="fs-32 fw-500 text-color4 mr-16">设为默认地址</view>
				<view class="fs-24 tip">每次下单都会默认使用该地址</view>
			</view>
			<u-switch v-model="model.defaultStatus" @change="change" activeColor="#FABB3C"> </u-switch>
		</view>

		<view :style="{ paddingBottom: safeAreaBottom + 'px' }" class="bot w-f ph-40" @click="toAddAdress">
			<view class="w-f h-96 b-96 f ai-c jc-c btn mb-32" @click="submit">
				<view class="fs-32 fw-500 text-color5">保存</view>
			</view>
		</view>
	</view>
	<!-- <City ref="city" @getCityDaya="getCityDaya" @close="close"/> -->
</template>
<script setup lang="ts">
	import { ref, getCurrentInstance } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { hotRegions } from '@/services/api/city';
	import { addressCreate, addressGet, addresUpdate } from '@/services/api/address';
	import City from '@/components/city/index.vue';
	const { proxy } = getCurrentInstance();
	const cityName = ref();
	const city = ref();
	const showCity=ref(false)
	const rules = {
		name: [
			{
				required: true,
				message: '不能为空',
				trigger: ['blur', 'change'],
			},
		],
		mobile: [
			{
				required: true,
				message: '不能为空',
				trigger: ['blur', 'change'],
			},
			{
				validator: (rule : any, value : any, callback : any) => {
					return uni.$u.test.mobile(value);
				},
				message: '手机号码不正确',
				// 触发器可以同时用blur和change
				trigger: ['change', 'blur'],
			},
		],
		areaId: [
			{
				validator: (rule : any, value : any, callback : any) => {
					if (!value) {
						callback(new Error('不能为空'));
					} else {
						callback();
					}
				},
				trigger: ['change', 'blur'],
			},
		]

	};
	const cityList=ref([])
	const model = ref({
		name: null,
		mobile: null,
		areaId: null,
		detailAddress: null,
		defaultStatus: false,
		id: null,
	});
	onLoad((options : any) => {
		if (options.id) {
			model.value.id = options.id;
			getDetail();
		}
		loadData()
	});
	
	function close(){
		showCity.value=false
	}
	async function loadData(){
		const res=await hotRegions()
		cityList.value=res.data
	}
	//详情
	async function getDetail() {
		const { data } = await addressGet({ id: model.value.id });
		for (let key in model.value) {
			model.value[key] = data[key];
		}
		cityName.value = data.areaName;
	}

	function submit() {
		proxy.$refs.formRef.validate().then(async () => {
			if (model.value.id) {
				await addresUpdate(model.value);
				uni.showToast({
					title: '修改成功',
					icon: 'none',
				});
			} else {
				await addressCreate(model.value);
				uni.showToast({
					title: '保存成功',
					icon: 'none',
				});
			}
			setTimeout(() => {
				uni.navigateBack();
			}, 1000);
		});
	}

	//获取弹框选择城市
	function getCityDaya(data : any) {
		cityName.value = `${data.parentName} ${data.name}`;
		model.value.areaId = data.id;
		showCity.value=false
	}
	function cityShow() {
		city.value.setShow();
		showCity.value=true
	}
	//点击定位
	function loaction() {
		uni.chooseLocation({
			success: function (res) {
				console.log(res.address)
				model.value.cityName = res.address
				model.value.detailAddress = res.name
				let location = res.latitude + ',' + res.longitude;
				uni.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=location',
					data: {
						location: location,
						key: 'X3HBZ-6K2CX-JRP4Z-ZH4VQ-K2YNZ-IMFFD', //自己申请的Key
					},
					method: 'GET',
					success(res) {
						cityName.value = res.data.result.address_component.province+res.data.result.address_component.city
						model.value.areaId=res.data.result.ad_info.adcode
						// console.log(res, '解析成功返回的参数');
					},
				});
			},
			fail: function (res) {
				console.log(res);
			},
		});
	}
	//底部安全距离
	const systemInfo = uni.getSystemInfoSync();
	let safeArea = systemInfo.safeArea;
	let screenHeight = systemInfo.screenHeight;
	let safeAreaBottom = screenHeight - safeArea.bottom;
</script>
<style lang="scss" scoped>
	.addAdress {
		background: #f8f8f8;
		min-height: 100vh;

		.bot {
			position: fixed;
			left: 0;
			bottom: 0;

			.btn {
				background: #fabb3c;
			}
		}

		::v-deep .u-form-item__body {
			padding: 44rpx 0 !important;
			border-color: #f8f8f8 !important;
		}

		.tip {
			color: #fa7f28;
		}

		.bg {
			background: #fff;
		}
	}
</style>